<template>
  <div ref="pdfContainer" class="pdf-container"></div>
</template>

<script>
import { useGetFileDataService } from '@/services/fileData'
import { useUserStore } from '@/stores/user'
import { ElNotification } from 'element-plus'
export default {
  name: 'PdfViewer',
  props: {
    url: {
      type: String
    }
  },
  mounted() {
    if (this.url) {
      useGetFileDataService({ userid: useUserStore().userid, filePath: this.url }).then((res) => {
        if (res.status === 200 && res.data.success) {
          this.loadPdf(res.data.file)
        } else {
          ElNotification({
            title: 'Error',
            message: res.data.message,
            type: 'error'
          })
        }
      })
    }
  },
  methods: {
    async loadPdf(file) {
      const loadingTask = window.pdfjsLib.getDocument(file)
      const scale = 1.5
      const refs = this.$refs

      const pdf = await loadingTask.promise
      // 渲染所有页面到canvas上
      var renderPage = function (num) {
        pdf.getPage(num).then(function (page) {
          var canvas = document.createElement('canvas')
          var context = canvas.getContext('2d')
          var viewport = page.getViewport({ scale: scale })

          // 调整canvas的高度以容纳新的页面
          canvas.height += viewport.height
          canvas.width = viewport.width

          // 渲染页面到canvas上
          var renderContext = {
            canvasContext: context,
            viewport: viewport
          }

          var renderTask = page.render(renderContext)
          renderTask.promise.then(function () {
            // 将canvas添加到容器中
            canvas.classList.add('pdf-page')
            refs.pdfContainer.appendChild(canvas)
            // 页面渲染完成，继续渲染下一页（如果有）
            if (num + 1 <= pdf.numPages) {
              renderPage(num + 1)
            } else {
              console.log('All pages rendered')
            }
          })
        })
      }

      // 从第一页开始渲染
      renderPage(1)
    }
  }
}
</script>

<style scoped>
.pdf-container {
  width: 100%;
  height: 100vh;
  overflow: auto;
  text-align: center;
}
</style>
